package com.hogocloud.corelibrary.http

import com.hogocloud.corelibrary.LibConfig
import com.hogocloud.corelibrary.http.interceptor.TokenInterceptor
import com.hogocloud.corelibrary.utils.LogUtils
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.math.log

/**
 * @author gjc
 * @version 1.0.0
 * @since 2018-05-06
 */

class HttpClientHelper private constructor() {

    var okHttpClient: OkHttpClient

    init {
        /**
         * 构建OkHttpClient
         */
        val builder = OkHttpClient.Builder()
        /**
         * 设置读取的超时时间
         */
        builder.readTimeout(50, TimeUnit.SECONDS)
        /**
         * 设置写入的超时时间
         */
        builder.writeTimeout(50, TimeUnit.SECONDS)
        /**
         * 设置连接的超时时间
         */
        builder.connectTimeout(50, TimeUnit.SECONDS)
        /**
         * 保持cookie持久化
         */
        builder.cookieJar(object : CookieJar {

            private val cookieStore = HashMap<String, List<Cookie>>()

            override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
                cookieStore[url.host()] = cookies
            }

            override fun loadForRequest(url: HttpUrl): List<Cookie> {
                val cookies = cookieStore[url.host()]
                return cookies ?: ArrayList()
            }
        })
        //确保支持重定向
        builder.followRedirects(true)
        //https支持
        builder.hostnameVerifier { _, _ -> true }
        //builder.sslSocketFactory(HttpsUtils.getSslSocketFactory());

        /**
         * 设置log拦截
         */
        if (LibConfig.isDebug()) {
            builder.addNetworkInterceptor(interceptor)
        }
        builder.addInterceptor(TokenInterceptor())
        /**
         * 公共参数拦截
         */
        //builder.addInterceptor(new CommonParamsInterceptor());

        okHttpClient = builder.build()

    }

    companion object {

        private val interceptor by lazy {
            HttpLoggingInterceptor() {
                LogUtils.i("okhttpBody", it)
            }.setLevel(HttpLoggingInterceptor.Level.BODY)
        }

        val instance by lazy {
            HttpClientHelper()
        }

    }
}
